import { getProfile } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'
import { login, getUserInfoByID } from '@/api/user'
import { setTimestamp } from '@/utils/auth'
import { resetRouter } from '@/router'

export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    setToken(state, payload) {
      state.token = payload
      setToken(payload)
      getToken()
    },
    delToken(state) {
      state.token = ''
      removeToken()
    },
    setUserInfo(state, payload) {
      state.userInfo = payload
    },
    delUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    // 登录
    async userLogin(context, payload) {
      const res = await login(payload)
      context.commit('setToken', res.data.data)
      setTimestamp() // 获取登录时的时间戳
    },
    // 获取用户信息
    async setUserInfo(context) {
      try {
        const res = await getProfile()
        const info = await getUserInfoByID(res.data.data.userId)
        context.commit('setUserInfo', { ...res.data.data, ...info.data.data })
        // console.log(res.data.data.roles.menus)
        return res.data.data.roles.menus
      } catch (error) {
        console.log(error)
      }
    },
    // 退出登录
    logout(context) {
      context.commit('delToken')
      context.commit('delUserInfo')
      resetRouter()
    }
  }
}
